package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.anno.GuiguCache;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.vo.album.AlbumCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper ;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper ;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper ;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper ;

	@Override
	public List<AlbumCategoryVo> getBaseCategoryList() {
		return baseCategoryViewMapper.getBaseCategoryList();
	}

	@Override
	public List<BaseAttribute> findAttribute(Long category1Id) {
		return baseAttributeMapper.findAttribute(category1Id) ;
	}

	@GuiguCache(cacheKey = RedisConstant.BASE_CATEGORY_VIEW_PREFIX +  "#{#params[0]}" ,
		enableLock = true ,
			lockName = RedisConstant.BASE_CATEGORY_VIEW_LOCK_PREFIX + "#{#params[0]}"
	)
	@Override
	public BaseCategoryView findCategoryByC3Id(Long c3Id) {
		return baseCategoryViewMapper.selectById(c3Id);
	}

	@Override
	public AlbumCategoryVo getBaseCategoryList(Long category1Id) {
		return baseCategoryViewMapper.getBaseCategoryListByC1Id(category1Id);
	}

	@Override
	public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {

		// 先根据一级分类的id查询二级分类数据
		LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>() ;
		baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id , category1Id) ;
		List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
		List<Long> c2Ids = baseCategory2List.stream().map(baseCategory2 -> baseCategory2.getId()).collect(Collectors.toList());

		// 再根据二级分类的id查询置顶三级分类数据
		// select * from base_category3 where category2_id in (1,2,3) and is_top = 1 limit 7
		LambdaQueryWrapper<BaseCategory3> baseCategory3LambdaQueryWrapper = new LambdaQueryWrapper<>() ;
		baseCategory3LambdaQueryWrapper.in(BaseCategory3::getCategory2Id , c2Ids ) ;
		baseCategory3LambdaQueryWrapper.eq(BaseCategory3::getIsTop , 1) ;
		baseCategory3LambdaQueryWrapper.last("limit 7") ;
		List<BaseCategory3> selectList = baseCategory3Mapper.selectList(baseCategory3LambdaQueryWrapper);

		return selectList;
	}

}
